package com.ad.pet.app.account.order;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.order.fragment.PacketInfoContract;
import com.ad.pet.app.account.order.fragment.PacketInfoPresenter;
import com.ad.pet.app.photo.model.ImageItem;
import com.ad.pet.common.data.http.HttpCode;
import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.PhotoManager;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.presenter.photo.PhotoContract;
import com.ad.pet.common.structure.presenter.photo.PhotoPresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.account.PicPath;
import com.ad.pet.models.remote.account.order.OrderType;
import com.ad.pet.models.remote.account.order.PayCompleted;
import com.ad.pet.models.remote.account.order.PayMethodAll;
import com.ad.pet.models.remote.account.order.PayUrl;
import com.ad.pet.models.remote.account.order.SignCheck;
import com.ad.pet.models.remote.account.order.UploadPic;
import com.ad.pet.models.result.ResultBean;
import com.ad.pet.utils.LyxUtils;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * Created by SEELE on 2019/3/6.
 */

public class ConfirmOrderActivity extends AppToolbarActivity implements PacketInfoContract.View, PhotoContract.View{
    @BindView(R.id.rb_normal)
    RatingBar mRbNormal;
    @BindView(R.id.et_aaa)
    EditText mEtAaa;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_ok)
    Button mBtnOk;
    private OrderType mOrderType;

    @Inject
    PacketInfoPresenter mPacketInfoPresenter;

    @Inject
    FileUtil mFileUtil;
    File mFile;
    @Inject
    PhotoPresenter mPhotoPresenter;
    @Inject
    RxDisposable mRxDisposable;
    @Inject
    PermissionManager mPermissionManager;

    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    private  PicPath mInitPicPath;//第一张的默认图

    private ArrayList<PicPath> mPhotos;//图片
    private MyAdapter mAdapter;




    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mToolbar.setTitle(getString(R.string.write_comment));
        mStatusLayoutManager.showContent();
    }

    @Override
    protected int contentLayout() {
        return R.layout.layout_comfirm_recive;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mPacketInfoPresenter.onCreate(this);
        mPhotoPresenter.onCreate(this);
        mOrderType = (OrderType) getIntent().getSerializableExtra(Constant.ORDER_PRODUCT_ID);
        mPermissionManager.setRxPermissions(new RxPermissions(mActivity));

        Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + getResources().getResourcePackageName(R.drawable.ic_upload_img) + "/"
                + getResources().getResourceTypeName(R.drawable.ic_upload_img) + "/"
                + getResources().getResourceEntryName(R.drawable.ic_upload_img));
        mInitPicPath = new PicPath(9999999999999999L, uri.toString(), null);

        mPhotos = new ArrayList<>();
        initPhotos();
        mAdapter = new MyAdapter(mPhotos);
        mRecyclerView.setLayoutManager(new GridLayoutManager(mActivity, 5));
        mRecyclerView.setAdapter(mAdapter);







        mDialogView = LayoutInflater.from(mActivity).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButOpen = mDialogView.findViewById(R.id.but_open);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);


        mPhotoDialog = new BottomSheetDialog(mActivity);
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);

    }

    @Override
    protected void initData() {




    }

    @Override
    protected void initEvents() {
        mBtnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Map<String,String> map = new HashMap<>();
//                for (int i = 0; i < mPhotos.size(); i++) {
//                    if (mPhotos.get(i).getId()!=9999999999999999L){
//                        map.put("jpg", Base64.encodeToString(LyxUtils.getBytes(mPhotos.get(i).getFile()),Base64.DEFAULT));
//                    }
//                }
                List<UploadPic> list = new ArrayList<>();
                for (int i = 0; i < mPhotos.size(); i++) {
                    if (mPhotos.get(i).getId()!=9999999999999999L){
                        list.add(new UploadPic(Base64.encodeToString(LyxUtils.getBytes(mPhotos.get(i).getFile()),Base64.DEFAULT)));
                    }
                }

                String json  = new Gson().toJson(list);
                json = json.replaceAll("\\{","[");
                json = json.replaceAll("\\}","]");
                json = json.replaceAll(":",",");
//                mPacketInfoPresenter.onComment(mOrderType.getOrder_id(),mOrderType.getProduct_id(),mOrderType.getOrder_product_id(),String.valueOf(mRbNormal.getRating()),mEtAaa.getText().toString(),json);
            }
        });
        mAdapter.setOnAddItemListener(new OnAddPhotoItemLinstener() {
            @Override
            public void onAdd(int position) {
//                if (mPhotos.size() >= 5) {
//                    ToastUtil.getToastUtil().showShort(context.getString(R.string.most_chose_4));
//                    return;
//                }
                BottomSheetUtil.collapsedDialog(mDialogView);
                mPhotoDialog.show();

            }
        });
        mAdapter.setOnDeleteItemListener(new OnDeleteItemListener() {
            @Override
            public void onDelete(int position) {
                mPhotos.remove(position);
                if (mPhotos.size() == 4 && mPhotos.get(0).getFile() != null) {
                    mPhotos.add(mInitPicPath);
                    Collections.sort(mPhotos);
                }
                mAdapter.notifyDataSetChanged();

            }
        });

        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        //打开相机
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                //打开相机
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        mFile = new File(mFileUtil.getRootDir(), System.currentTimeMillis() + ".jpg");
                        //打开相机
//                        if (maxPhoto - mAdapter.getData().size() - 1 > 0) {
                        PhotoManager.openCamera(mActivity, mFile, PhotoManager.REQUEST_CODE_OPEN_CAMERA);

//                        } else {
//                            ToastUtil.getToastUtil().showShort(context.getString(R.string.most_chose_4));
//                        }
                    }
                }, getString(R.string.camera), Manifest.permission.CAMERA));
            }
        });

        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Navigation.goPhotoLoaderActivity(mActivity, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
                    }
                }, mActivity.getString(R.string.storage), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE));
            }
        });

        mRbNormal.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if (rating<1){
                    ratingBar.setRating(1);
                }
            }
        });
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void error(int code, String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void onConfirmReciveSuccess(ResultBean resultBean) {

    }


    @Override
    public void onCommentSuccess(ResultBean resultBean) {
            if (HttpCode.SUCCESS.equals(resultBean.getCode())){
                ToastUtil.getToastUtil().showShort(getString(R.string.comment_success));
                finish();
            }else {
                ToastUtil.getToastUtil().showShort(resultBean.getMsg());
            }


    }

    @Override
    public void createOrderSuccess(PayUrl payUrl) {

    }


    @Override
    public void getPayWaysSuccess(PayMethodAll payMethodAll) {

    }

    @Override
    public void addPayAdvice() {

    }

    @Override
    public void payCompletedSuccess(PayCompleted payCompleted) {

    }

    @Override
    public void payCompletedOpenSuccess(SignCheck signCheck) {

    }

    @Override
    public void compressComplete(File file) {

            if (mPhotos.size() == 5) {
                mPhotos.set(0, new PicPath(System.currentTimeMillis(), file.toURI().getPath(), file));
                Collections.sort(mPhotos);
            } else {
                mPhotos.add(new PicPath(System.currentTimeMillis(), file.toURI().getPath(), file));
            }

            mAdapter.notifyDataSetChanged();

    }

    @Override
    public void photoCallback(String path) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRxDisposable!=null)
            mRxDisposable.clear();
    }

    private void initPhotos() {
        mPhotos.add(mInitPicPath);
        Collections.sort(mPhotos);
    }



    class MyAdapter extends BaseQuickAdapter<PicPath, BaseViewHolder> {
        //        int mustCount = 5;
        private OnDeleteItemListener mOnDeleteItemListener;
        private OnAddPhotoItemLinstener mOnAddPhotoItemLinstener;

        public MyAdapter(@Nullable List<PicPath> data) {
            super(R.layout.item_photo_suggest_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final PicPath item) {
            ImageView ivDelete = helper.getView(R.id.iv_delete);
            ImageView ivPhoto = helper.getView(R.id.iv_photo);
            ImageView ivUpdate = helper.getView(R.id.iv_update);
            if (item.getId() != 9999999999999999L) {
                GlideUtil.load(mContext, item.getPic_path(), ivPhoto);
            }
            ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnDeleteItemListener.onDelete(helper.getLayoutPosition());
                }
            });
            if (item.getId() == 9999999999999999L) {
                ivDelete.setVisibility(View.GONE);
                ivUpdate.setVisibility(View.VISIBLE);
                ivPhoto.setVisibility(View.GONE);
                ivUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnAddPhotoItemLinstener.onAdd(helper.getLayoutPosition());
                    }
                });
            } else {
                ivDelete.setVisibility(View.VISIBLE);
                ivUpdate.setVisibility(View.GONE);
                ivPhoto.setVisibility(View.VISIBLE);
                ivUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Navigation.goPhotoLoaderActivity((Activity) mContext, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);

                    }
                });
            }



        }

        public void setOnDeleteItemListener(OnDeleteItemListener listener) {
            if (listener != null) {
                this.mOnDeleteItemListener = listener;
            }
        }

        public void setOnAddItemListener(OnAddPhotoItemLinstener listener) {
            if (listener != null) {
                this.mOnAddPhotoItemLinstener = listener;
            }
        }


    }

    public interface OnDeleteItemListener {
        void onDelete(int position);
    }

    public interface OnAddPhotoItemLinstener {
        void onAdd(int position);
    }

    public void onSetFiles(File file) {
        Logger.e("setThread:" + Thread.currentThread());
        if (mPhotos.size() == 5) {
            mPhotos.set(0, new PicPath(System.currentTimeMillis(), file.toURI().getPath(), file));
            Collections.sort(mPhotos);
        } else {
            mPhotos.add(new PicPath(System.currentTimeMillis(), file.toURI().getPath(), file));
        }

        mAdapter.notifyDataSetChanged();
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PhotoManager.REQUEST_CODE_CHECK_IMAGE:
                    //选择图片回调 并裁剪
                    ArrayList<ImageItem> path = data.getParcelableArrayListExtra("path");
//                    mFile = new File(mFileUtil.getHeaderDir().getPath(), System.currentTimeMillis() + ".jpg");
                    mPhotoPresenter.compressPhoto(new File(path.get(0).getImagePath()));
//                    PhotoManager.crop(this, mFile, new File(path.get(0).getImagePath()), PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_OPEN_CAMERA:
                    //相机回调
//                    PhotoManager.crop(this, mFile, mFile, PhotoManager.REQUEST_CODE_CROP_CODE);
                    if (mFile != null)
                        mPhotoPresenter.compressPhoto(mFile);
                    break;
                case PhotoManager.REQUEST_CODE_CROP_CODE:
                    //裁剪回调
                    //压缩
                    break;

            }
        }

    }

}
